<?php

define(AppId, "wx30e178a8e4d9bd88");//定义AppId，需要在微信公众平台申请自定义菜单后会得到
 
define(AppSecret, "30d030d55b0358c5d9c8640214218666");//定义AppSecret，需要在微信公众平台申请自定义菜单后会得到

$wechatObj = new Wechats();//实例化微信类
 
$creatMenu = $wechatObj->creatMenu();//创建菜单

class Wechats
 {
 private function getAccessToken() //获取access_token
 {
 $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".AppId."&secret=".AppSecret;
 $data = getCurl($url);//通过自定义函数getCurl得到https的内容
 $resultArr = json_decode($data, true);//转为数组
 return $resultArr["access_token"];//获取access_token
 }
 
public function creatMenu()//创建菜单
 {
 $accessToken = $this->getAccessToken();//获取access_token
 
 $menuPostString = '{
 	"button":
 	[
		{
			"name": "看文章",
			"sub_button":
			[
				{
					"type":"click",
	 				"name":"最新文章",
	 				"key":"list"
	 			},
	 			{	
					"type":"click",
	 				"name":"随机文章",
	 				"key":"default"
	 			},
	 			{	
					"type":"click",
	 				"name":"最新文章",
	 				"key":"list"
	 			},
	 			{	
					"type":"click",
	 				"name":"随机文章",
	 				"key":"default"
	 			}
			]
		},
		{
			"name":"我的博客",
			"type":"view",
			"url": "http://www.xiaocainiao.net/"
		 },
		 {
			"name":"我的博客",
			"type":"view",
			"url": "http://www.xiaocainiao.net/"
		 },
 	]
 }';
 $menuPostUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$accessToken;//POST的url
 $menu = dataPost($menuPostString, $menuPostUrl);//将菜单结构体POST给微信服务器
 }
 }
 
function getCurl($url){//get https的内容
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL,$url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);//不输出内容
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
 $result =  curl_exec($ch);
 curl_close ($ch);
 return $result;
 }
 
function dataPost($post_string, $url) {//POST方式提交数据
 $context = array ('http' => array ('method' => "POST", 'header' => "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) \r\n Accept: */*", 'content' => $post_string ) );
 $stream_context = stream_context_create ( $context );
 $data = file_get_contents ( $url, FALSE, $stream_context );
 return $data;
 }